package com.googlecode.grima.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;

public class IOUtil {
	
	public static final int BUFFER_SIZE = 8192; // 8Kb
	
	public static void copyStream(InputStream is, OutputStream os){
		
		if (is != null){
			
			try {
	
				BufferedOutputStream bos = new BufferedOutputStream(os, BUFFER_SIZE);
	
				byte[] content;
	
				try {
					
					byte[] buffer = new byte[8192];
					BufferedInputStream bis = new BufferedInputStream(is, BUFFER_SIZE);
	
					ByteArrayOutputStream baos = new ByteArrayOutputStream();
					int len = 0;
					while ((len = bis.read(buffer, 0, buffer.length)) != -1)
					{
						baos.write(buffer, 0, len);
					}
					content = baos.toByteArray();
					bis.close();
					is.close();
				}
				catch (Exception e) {
					throw new ServletException(e);
				}
	
				bos.write(content, 0, content.length);
				bos.flush();
				bos.close();
				os.flush();
				os.close();
	
			}
			catch (Exception e) {
				//nada a fazer
			}
		
		}

	}

}
